<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="我的会议" name="my">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>我的会议</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="handleAdd">发起会议</el-button>
          </div>
          
          <!-- 搜索区域 -->
          <el-form :inline="true" :model="queryParams" class="demo-form-inline">
            <el-form-item label="会议主题">
              <el-input v-model="queryParams.title" placeholder="请输入会议主题" clearable></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option label="未开始" :value="0"></el-option>
                <el-option label="进行中" :value="1"></el-option>
                <el-option label="已结束" :value="2"></el-option>
                <el-option label="已取消" :value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          
          <!-- 表格区域 -->
          <el-table
            v-loading="loading"
            :data="meetingList"
            border
            style="width: 100%">
            <el-table-column
              prop="title"
              label="会议主题"
              width="180">
            </el-table-column>
            <el-table-column
              prop="roomName"
              label="会议室"
              width="120">
            </el-table-column>
            <el-table-column
              label="会议时间"
              width="240">
              <template slot-scope="scope">
                {{ scope.row.startTime | formatDateTime }} 至 {{ scope.row.endTime | formatDateTime }}
              </template>
            </el-table-column>
            <el-table-column
              prop="status"
              label="状态"
              width="100">
              <template slot-scope="scope">
                <el-tag :type="getMeetingStatusType(scope.row.status)">
                  {{ getMeetingStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="200">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleDetail(scope.row)">详情</el-button>
                <el-button
                  v-if="scope.row.status === 0"
                  size="mini"
                  type="primary"
                  @click="handleEdit(scope.row)">编辑</el-button>
                <el-button
                  v-if="scope.row.status === 0"
                  size="mini"
                  type="danger"
                  @click="handleCancel(scope.row)">取消</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页区域 -->
          <div class="pagination-container">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryParams.page"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="queryParams.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="待参加会议" name="pending">
        <pending-meetings @refresh="getStatistics" />
      </el-tab-pane>
      
      <el-tab-pane label="会议统计" name="statistics">
        <meeting-statistics :statistics="statistics" />
      </el-tab-pane>
    </el-tabs>
    
    <!-- 会议表单对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="650px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="会议主题" prop="title">
          <el-input v-model="form.title" placeholder="请输入会议主题"></el-input>
        </el-form-item>
        <el-form-item label="会议室" prop="roomId">
          <el-select 
            v-model="form.roomId" 
            placeholder="请选择会议室" 
            filterable 
            :disabled="!!form.id"
            @change="handleRoomChange">
            <el-option
              v-for="item in roomOptions"
              :key="item.id"
              :label="item.name + ' (' + item.location + ', 容纳' + item.capacity + '人)'"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会议时间" prop="timeRange">
          <el-date-picker
            v-model="form.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :disabled="!!form.id"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="参与人员" prop="participantIds">
          <el-select
            v-model="form.participantIds"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词搜索"
            :remote-method="remoteMethod"
            :loading="userLoading"
            style="width: 100%">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.name + ' (' + item.deptName + ')'"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会议议程" prop="agenda">
          <el-input type="textarea" v-model="form.agenda" placeholder="请输入会议议程" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 会议详情对话框 -->
    <el-dialog title="会议详情" :visible.sync="detailVisible" width="700px">
      <meeting-detail v-if="detailVisible" :meeting-id="detailId" />
    </el-dialog>
  </div>
</template>

<script>
import { listMeetings, createMeeting, updateMeeting, cancelMeeting, getMeetingStatistics } from '@/api/meeting'
import { getAvailableRooms } from '@/api/meeting/room'
import { searchUsers } from '@/api/system/user'
import PendingMeetings from './components/PendingMeetings'
import MeetingStatistics from './components/MeetingStatistics'
import MeetingDetail from './components/MeetingDetail'

export default {
  name: 'MeetingList',
  components: {
    PendingMeetings,
    MeetingStatistics,
    MeetingDetail
  },
  data() {
    return {
      // 激活的标签页
      activeTab: 'my',
      // 遮罩层
      loading: false,
      // 会议列表
      meetingList: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        title: undefined,
        status: undefined
      },
      // 弹出层标题
      dialogTitle: '',
      // 是否显示弹出层
      dialogVisible: false,
      // 详情弹出层
      detailVisible: false,
      // 详情ID
      detailId: null,
      // 表单参数
      form: {
        id: undefined,
        title: '',
        roomId: undefined,
        timeRange: [],
        participantIds: [],
        agenda: ''
      },
      // 会议室选项
      roomOptions: [],
      // 用户选项
      userOptions: [],
      // 用户加载状态
      userLoading: false,
      // 统计数据
      statistics: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: '会议主题不能为空', trigger: 'blur' }
        ],
        roomId: [
          { required: true, message: '会议室不能为空', trigger: 'change' }
        ],
        timeRange: [
          { required: true, message: '会议时间不能为空', trigger: 'change' }
        ],
        participantIds: [
          { required: true, message: '参与人员不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getStatistics()
  },
  methods: {
    // 获取会议列表
    getList() {
      this.loading = true
      listMeetings(this.queryParams).then(response => {
        this.meetingList = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    // 获取统计数据
    getStatistics() {
      getMeetingStatistics().then(response => {
        this.statistics = response.data
      })
    },
    // 查询按钮操作
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    // 重置按钮操作
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        title: undefined,
        status: undefined
      }
      this.handleQuery()
    },
    // 新增按钮操作
    handleAdd() {
      this.reset()
      this.dialogTitle = '发起会议'
      this.dialogVisible = true
      this.loadAvailableRooms()
    },
    // 编辑按钮操作
    handleEdit(row) {
      this.reset()
      this.form.id = row.id
      this.form.title = row.title
      this.form.roomId = row.roomId
      this.form.agenda = row.agenda
      
      // 加载参与人员
      const participantIds = row.participants ? row.participants.map(p => p.userId) : []
      this.form.participantIds = participantIds
      
      this.dialogTitle = '编辑会议'
      this.dialogVisible = true
      this.loadAvailableRooms()
    },
    // 取消会议
    handleCancel(row) {
      this.$confirm('是否确认取消会议主题为"' + row.title + '"的会议?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return cancelMeeting(row.id)
      }).then(() => {
        this.getList()
        this.$message.success('取消成功')
      }).catch(() => {})
    },
    // 查看详情
    handleDetail(row) {
      this.detailId = row.id
      this.detailVisible = true
    },
    // 加载可用会议室
    loadAvailableRooms() {
      if (this.form.timeRange && this.form.timeRange.length === 2) {
        const startTime = this.form.timeRange[0]
        const endTime = this.form.timeRange[1]
        getAvailableRooms(startTime, endTime).then(response => {
          this.roomOptions = response.data
        })
      } else {
        getAvailableRooms(new Date(), new Date()).then(response => {
          this.roomOptions = response.data
        })
      }
    },
    // 会议室变更
    handleRoomChange() {
      // 可以在这里添加逻辑，例如根据会议室容量限制参与人数
    },
    // 远程搜索用户
    remoteMethod(query) {
      if (query !== '') {
        this.userLoading = true
        searchUsers(query).then(response => {
          this.userOptions = response.data
          this.userLoading = false
        })
      } else {
        this.userOptions = []
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: '',
        roomId: undefined,
        timeRange: [],
        participantIds: [],
        agenda: ''
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const data = {
            id: this.form.id,
            title: this.form.title,
            roomId: this.form.roomId,
            participantIds: this.form.participantIds,
            agenda: this.form.agenda
          }
          
          if (this.form.timeRange && this.form.timeRange.length === 2) {
            data.startTime = this.form.timeRange[0]
            data.endTime = this.form.timeRange[1]
          }
          
          if (this.form.id) {
            updateMeeting(data).then(response => {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.getList()
            })
          } else {
            createMeeting(data).then(response => {
              this.$message.success('创建成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    // 每页数量变化
    handleSizeChange(val) {
      this.queryParams.size = val
      this.getList()
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.getList()
    },
    // 标签页切换
    handleTabClick() {
      if (this.activeTab === 'my') {
        this.getList()
      } else if (this.activeTab === 'statistics') {
        this.getStatistics()
      }
    },
    // 获取会议状态文本
    getMeetingStatusText(status) {
      const statusMap = {
        0: '未开始',
        1: '进行中',
        2: '已结束',
        3: '已取消'
      }
      return statusMap[status] || '未知'
    },
    // 获取会议状态类型
    getMeetingStatusType(status) {
      const typeMap = {
        0: 'primary',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      return typeMap[status] || ''
    }
  }
}
</script>

<style scoped>
.pagination-container {
  margin-top: 15px;
}
</style> 